﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using ClientLib.Common;
using bus = WpfDataBingding.TaskServiceReference;//debug



namespace WpfDataBingding.DevTreeData
{
    public class DataBus
    {
        //string dataBusID;
        ObservableCollection<MonitorAgent> monitorAgentList;

        public ObservableCollection<MonitorAgent> MonitorAgentList
        {
            get { return monitorAgentList; }
            set { monitorAgentList = value; }
        }

        /// <summary>
        /// 通过远程调用填充数据总线设备实例，包括是否被监控的信息
        /// </summary>
        public void fillDataBusByRemoteService(bus.DataBusServiceClient dBSC,string userID)
        {
            //string userID = Application.Current.Properties["userID"] as string;
             
            TaskServiceReference.MonAgentInfo[] monAgentInfoArray = null;
            try
            {
                //调用远程服务
                monAgentInfoArray = dBSC.QueryMonAgentsDevs();
                //刷新设备实例信息
                initFromDataContractObj(monAgentInfoArray);
                //刷新设备监控信息
                bus.UserMonTask usertask = dBSC.QueryUserTask(userID);
                initDevMonStatusFromDataContractObj(usertask);
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        /// <summary>
        /// 通过远程调用填充数据总线设备实例，包括是否被监控的信息
        /// </summary>
        public void fillDataBusByRemoteService(string userID)
        {
            //string userID = Application.Current.Properties["userID"] as string;

            bus.DataBusServiceClient dBSC = new bus.DataBusServiceClient();
            TaskServiceReference.MonAgentInfo[] monAgentInfoArray = null;
            try
            {
                //调用远程服务
                monAgentInfoArray = dBSC.QueryMonAgentsDevs();
                //刷新设备实例信息
                initFromDataContractObj(monAgentInfoArray);
                //刷新设备监控信息
                bus.UserMonTask usertask = dBSC.QueryUserTask(userID);
                initDevMonStatusFromDataContractObj(usertask);                
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                if (dBSC != null)
                    dBSC.Close();
            }
        }

        /// <summary>
        /// 将从数据总线获取的监控状态列表信息刷新到当前设备集合
        /// </summary>
        public void initDevMonStatusFromDataContractObj(bus.UserMonTask usertask)
        {
            bus.UserMonTaskSub[] monTaskArray = usertask.MonTaskList;
            foreach (MonitorAgent monitorAgent in MonitorAgentList)
            {
                foreach (Device dev in monitorAgent.DeviceList)
                {
                    bool isMonitered = false;
                    for (int i = 0; i < monTaskArray.Length; i++)
                    {
                        if (monTaskArray[i].DevID == dev.DevID)//说明被监控
                        {
                            dev.setMoniterStatus();
                            isMonitered = true;
                            break;
                        }
                    }
                    if (isMonitered == false)
                        dev.cancelMoniterStatus();
                }
            }
        }

        /// <summary>
        /// 将从数据总线获取的监控代理列表信息转化为对应的本地类型
        /// </summary>
        /// <param name="monAgentList">从数据总线获取的监控代理列表</param>
        public void initFromDataContractObj(bus.MonAgentInfo[] monAgentArray)
        {
            this.monitorAgentList = new ObservableCollection<MonitorAgent>();

            for (int i = 0; i < monAgentArray.Length; i++)
            {
                bus.MonAgentInfo monAgent = monAgentArray[i];//取出一个MonAgentInfo元素引用

                //新建一个MonitorAgent对象
                MonitorAgent monAgent_new = new MonitorAgent();
                monAgent_new.ID = monAgent.Id;
                monAgent_new.DeviceList = new ObservableCollection<Device>();
                //依次初始化monAgent_new的每个设备
                foreach (bus.MonDeviceInfo devInfo in monAgent.MonDevList)
                {
                    //新建一个Device对象
                    Device device_new = new Device();

                    device_new.MonAgentBelongTo = monAgent_new;//添加设备对其所属监控代理的引用
                    //利用数据契约对应对象初始化
                    device_new.DevID = devInfo.Id;
                    device_new.DevType = devInfo.Type;
                    device_new.Name = devInfo.Name;

                    //初始化静态属性集合
                    device_new.StaticStateList = new ObservableCollection<StaticState>();
                    foreach (bus.StaticAttribute staticAttribute in devInfo.StaticAttrList)
                    {
                        //新建一个StaticState对象
                        StaticState sState_new = new StaticState();
                        sState_new.DeviceBelongTo = device_new;//添加状态对其所属设备的引用
                        sState_new.Name = staticAttribute.AttrName;
                        AttributeValue attrVal_new = new AttributeValue();
                        try
                        {
                            attrVal_new.setDataValue(AttributeValue.mapType(staticAttribute.AttrValueType),
                                                     staticAttribute.AttrValue);
                            sState_new.AttributeValue = attrVal_new;
                        }
                        catch (Exception e)
                        {
                            throw new ApplicationException("数据契约静态属性'" + staticAttribute.AttrName + "'转化为本地类型中，值转化出错:" + e.Message, e);
                        }
                        device_new.StaticStateList.Add(sState_new);//将新静态属性添加到新静态属性列表
                    }

                    //初始化动态属性集合
                    device_new.DynamicStateList = new ObservableCollection<DynamicState>();
                    foreach (bus.State dState in devInfo.StateList)
                    {
                        //新建一个StaticState对象
                        DynamicState dState_new = new DynamicState();
                        dState_new.DeviceBelongTo = device_new;//添加状态对其所属设备的引用
                        dState_new.Name = dState.DsName;
                        dState_new.Title = dState.DsTitle;
                        dState_new.Unit = dState.DsUnit;
                        dState_new.ViewType = dState.DsViewType;
                        dState_new.AttributeValue = new AttributeValue();
                        try
                        {
                            dState_new.AttributeValue.setDataValue(AttributeValue.mapType(dState.DsValueType),
                                                     dState.DsDefaultValue);
                        }
                        catch (Exception e)
                        {
                            throw new ApplicationException("数据契约动态属性'" + dState.DsName + "'转化为本地类型中，值转化出错:" + e.Message, e);
                        }

                        device_new.DynamicStateList.Add(dState_new);//将新静态属性添加到新静态属性列表
                    }

                    monAgent_new.DeviceList.Add(device_new);//将新设备添加到设备列表
                }//devInfo

                this.monitorAgentList.Add(monAgent_new);//将新监控代理添加到代理列表
            }//monAgent
        }

        /// <summary>
        /// 获取数据总线下特定类型的所有设备
        /// </summary>
        /// <param name="devTypeName">设备类型名</param>
        /// <returns>设备列表</returns>
        public List<Device> getCertainDevTypeList(string devTypeName)
        {
            List<Device> devList=new List<Device>(4);
            foreach (MonitorAgent monitorAgent in MonitorAgentList)
            {
                foreach (Device dev in monitorAgent.DeviceList)
                {
                    if (dev.DevType == devTypeName)
                        devList.Add(dev);
                }
            }
            return devList;
        }

        /// <summary>
        /// 调用远程服务，刷新所有设备的监控信息
        /// </summary>
        /// <returns></returns>
        public void renewMonInfOfAllDev(string userID)
        {
            //调用陈显勇模块，调用服务刷新正在被监控设备列表
            try
            {
                new ClientLib.Common.InitMonDevice(userID);       
            }
            catch (Exception e)
            {                
                throw e;
            }
                             
            foreach (MonitorAgent monitorAgent in MonitorAgentList)
            {
                foreach (Device dev in monitorAgent.DeviceList)
                {
                    dev.addDeviceMoniterInfo(userID);
                }
            }
        }

        /// <summary>
        /// 获取被监控的设备列表
        /// </summary>
        /// <returns></returns>
        public List<Device> getMonitedDevList()
        {
            List<Device> devList = new List<Device>(4);
            foreach (MonitorAgent monitorAgent in MonitorAgentList)
            {
                foreach (Device dev in monitorAgent.DeviceList)
                {
                    if (dev.IsMonitered)
                        devList.Add(dev);
                }
            }
            return devList;
        }

        /// <summary>
        /// for debug
        /// </summary>
        /// <returns></returns>
        public static DataBus create_DataBus()
        {
            Device dev1 = new Device();
            dev1.Name = "dev1";
            dev1.DevType = "XBPQ";
            Device dev2 = new Device();
            dev2.Name = "dev2";
            dev2.DevType = "XBPQ";
            Device dev3 = new Device();
            dev3.Name = "dev3";
            dev3.DevType = "XBPQ";
            Device dev4 = new Device();
            dev4.Name = "dev4";
            dev4.DevType = "XBPQ";

            MonitorAgent ma1 = new MonitorAgent();
            ma1.ID="mon1";
            ObservableCollection<Device> devColl = new ObservableCollection<Device>();
            devColl.Add(dev1);            
            devColl.Add(dev2);
            ma1.DeviceList = devColl;

            MonitorAgent ma2 = new MonitorAgent();
            ma2.ID = "mon2";
            ObservableCollection<Device> devCol2 = new ObservableCollection<Device>();
            devCol2.Add(dev3);
            devCol2.Add(dev4);
            ma2.DeviceList = devCol2;

            ObservableCollection<MonitorAgent> monList = new ObservableCollection<MonitorAgent>();
            monList.Add(ma1);
            monList.Add(ma2);

            DataBus db = new DataBus();
            db.monitorAgentList = monList;
            return db;
        }


    }
}
